package course.cmsc436.medicationmanager;

import java.util.ArrayList;
import java.util.Calendar;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class AddMedicationActivity extends Activity {

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_med);
		

		final EditText name = (EditText) findViewById(R.id.addMedByNameEntry);	
		final Spinner numPills = (Spinner) findViewById(R.id.numPillSpinner);
		final Spinner pillFreq = (Spinner) findViewById(R.id.pillFreqSpinner);
		final CheckBox makeAlarm = (CheckBox) findViewById(R.id.alarmCheckbox);
			
		Button scanButton = (Button) findViewById(R.id.addByScanButton);
		scanButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//scanning happens here
				IntentIntegrator ii = new IntentIntegrator(AddMedicationActivity.this);
				ii.initiateScan();
				//name.setText("...")
			}
		});
		
		
		//time pickers for each dose
		final EditText time1 = (EditText) findViewById(R.id.doseTime1);
		time1.setEnabled(false);
		time1.setOnClickListener(new OnClickListener() {

	        @Override
	        public void onClick(View v) {
	            onClickTime(time1);
	        }
	    });
				
		final EditText time2 = (EditText) findViewById(R.id.doseTime2);
		time2.setEnabled(false);
		time2.setOnClickListener(new OnClickListener() {

	        @Override
	        public void onClick(View v) {
	            onClickTime(time2);
	        }
	    });
		
		final EditText time3 = (EditText) findViewById(R.id.doseTime3);
		time3.setEnabled(false);
		time3.setOnClickListener(new OnClickListener() {

	        @Override
	        public void onClick(View v) {
	            onClickTime(time3);
	        }
	    });
		
		final EditText time4 = (EditText) findViewById(R.id.doseTime4);
		time4.setEnabled(false);
		time4.setOnClickListener(new OnClickListener() {

	        @Override
	        public void onClick(View v) {
	            onClickTime(time4);
	        }
	    });
		
		pillFreq.setSelection(1);
		
		pillFreq.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				//enable/disable fields
				switch (Integer.parseInt((String)pillFreq.getSelectedItem())) {
					case 1:
						time1.setEnabled(true);
						time2.setText("");
						time2.setEnabled(false);
						time2.setVisibility(View.INVISIBLE);
						time3.setText("");
						time3.setEnabled(false);
						time3.setVisibility(View.INVISIBLE);
						time4.setText("");
						time4.setEnabled(false);
						time4.setVisibility(View.INVISIBLE);
						break;
					case 2:
						time1.setEnabled(true);
						time2.setEnabled(true);
						time3.setText("");
						time3.setEnabled(false);
						time3.setVisibility(View.INVISIBLE);
						time4.setText("");
						time4.setEnabled(false);
						time4.setVisibility(View.INVISIBLE);
						break;
					case 3:
						time1.setEnabled(true);
						time2.setEnabled(true);
						time3.setEnabled(true);
						time4.setText("");
						time4.setEnabled(false);
						time4.setVisibility(View.INVISIBLE);
						break;
					default:
						time1.setEnabled(true);
						time2.setEnabled(true);
						time3.setEnabled(true);
						time4.setEnabled(true);
						break;
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				//do nothing
			}
			
		});
		
		//button for canceling add medication
		Button cancelButton = (Button) findViewById(R.id.cancelButton);
		cancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
		
		//button for submit
		Button submitButton = (Button) findViewById(R.id.submitButton);
		submitButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//check to see if necessary fields are filled
				if ( name.getText().toString().equals("") || ((String)numPills.getSelectedItem()).equals("") ||
						((String)pillFreq.getSelectedItem()).equals("")) {
					Toast msg = Toast.makeText(getApplicationContext(), "Please complete the necessary information.", Toast.LENGTH_SHORT);
					msg.show();
				}
					else {
					Intent data = new Intent();
					data.putExtra("medName", name.getText().toString());
					data.putExtra("pillsPerDose", Integer.parseInt((String)numPills.getSelectedItem()));
					data.putExtra("dosesPerDay", Integer.parseInt((String)pillFreq.getSelectedItem()));
					
					ArrayList<String> times = new ArrayList<String>();
					times.add(time1.getText().toString());
					times.add(time2.getText().toString());
					times.add(time3.getText().toString());
					times.add(time4.getText().toString());
					
					data.putExtra("doseTimes", times);
					data.putExtra("setAlarm", makeAlarm.isChecked());
					
					setResult(RESULT_OK, data);
					
					finish();
				}
			}
		});
	}
	
	//time picker dialog appears when selecting time EditText
	private void onClickTime(final EditText timeView) {
        Calendar mCurrentTime = Calendar.getInstance();
        int hour = mCurrentTime.get(Calendar.HOUR_OF_DAY);
        int minute = mCurrentTime.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(AddMedicationActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                timeView.setText( selectedHour + ":" + selectedMinute);
            }
        }, hour, minute, true);
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
		if (scanningResult != null) {
			//we have a result
			String scanContent = scanningResult.getContents();

			if(scanContent.length()<11){ // for now a basic check of the input
				Toast toast = Toast.makeText(getApplicationContext(),
						"invalid NDC BARCODE!", Toast.LENGTH_SHORT);
				toast.show();
			}
			
			final EditText name = (EditText) findViewById(R.id.addMedByNameEntry);
			name.setText("Searching...");
			name.setEnabled(false);
			
			NDCFetcher.doAsync(scanContent, new NDCFetcher.FetchCompleteListener() {
				@Override
				public void onFetchComplete(String desc) {
					name.setText(desc);
					name.setEnabled(true);
				}
			});
		}else{
			Toast toast = Toast.makeText(getApplicationContext(),
					"No scan data received!", Toast.LENGTH_SHORT);
			toast.show();
		}
	}

}
